/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package cinescope2014.essais;

import java.sql.*;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.DefaultCellEditor;
import javax.swing.JComboBox;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellEditor;
import javax.swing.table.TableColumn;

/**
 *
 * @author pascal
 */
public class Table7JCombo extends javax.swing.JFrame {

    /*
     * ATTRIBUTS
     */
    private Connection icn;
    private PreparedStatement ipstSQL;
    private ResultSet irs;
    private Object[] tEntetes = null;
    private Object[][] tDataTable = null;
    private Object[] tDataLigne = null;
    private DefaultTableModel idtmVilles;

    /**
     * Creates new form Table7JCombo
     */
    public Table7JCombo() {
        super("Table7JCombo");

        initComponents();

        setLocationRelativeTo(null);

        try {

            Class.forName("org.gjt.mm.mysql.Driver");
            icn = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/cours", "root", "");

            ipstSQL = icn.prepareStatement("SELECT cp, nom_ville FROM villes");
            irs = ipstSQL.executeQuery();

            // --- Recuperation de la structure du curseur
            ResultSetMetaData lrsmd = irs.getMetaData();

            // --- Nombre de colonnes du curseur
            int liColonnes = lrsmd.getColumnCount();

            // --- Noms des colonnes
            tEntetes = new Object[liColonnes + 1];
            for (int liNumeroColonne = 0; liNumeroColonne < liColonnes; liNumeroColonne++) {
                tEntetes[liNumeroColonne] = lrsmd.getColumnName(liNumeroColonne + 1);
            }
            tEntetes[liColonnes] = "Liste des pays";

            // --- Pour les donnees de la JTable
            // --- Pour obtenir le nombre de lignes du curseur
            irs.last();
            int liLignes = irs.getRow();
            tDataTable = new Object[liLignes][liColonnes];

            irs.beforeFirst();
            int liNumeroLigne = 0;
            // --- Balayage des lignes
            while (irs.next()) {
                // --- Balayage des colonnes pour construire une ligne
                tDataLigne = new Object[liColonnes + 1];
                for (int liNumeroColonne = 0; liNumeroColonne < liColonnes; liNumeroColonne++) {
                    if (irs.getObject(liNumeroColonne + 1) == null) {
                        tDataLigne[liNumeroColonne] = "NUL";
                    } else {
                        tDataLigne[liNumeroColonne] = irs.getObject(liNumeroColonne + 1).toString();
                    }
                }

                //tDataLigne[liColonnes] = "France";
                tDataLigne[liColonnes] = "";

                tDataTable[liNumeroLigne] = tDataLigne;
                liNumeroLigne++;
            }

            // --- Affectation des tableaux d'objets a la JTable
            this.idtmVilles = new DefaultTableModel(this.tDataTable, this.tEntetes);
            jTableVilles.setModel(this.idtmVilles);

            /*
             * LA COLONNE SPECIALE (APRES LE REMPLISSAGE DE LA JTABLE)
             */
            JComboBox jcbxPays = new JComboBox();
            jcbxPays.addItem("France");
            jcbxPays.addItem("Italie");
            jcbxPays.addItem("Espagne");

            TableColumn tableColonnePays = jTableVilles.getColumnModel().getColumn(2);

            TableCellEditor tableCelluleEditeur = new DefaultCellEditor(jcbxPays);
            tableColonnePays.setCellEditor(tableCelluleEditeur);

            // Largeur de la colonne de la JTable
            tableColonnePays.setPreferredWidth(300);

            // Fermetures
            irs.close();
            ipstSQL.close();
            icn.close();

        } /// du try
        catch (ClassNotFoundException | SQLException e) {
            jLabelMessage.setText(e.getMessage());
        }
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabelMessage = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTableVilles = new javax.swing.JTable();
        jButtonTester = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosing(java.awt.event.WindowEvent evt) {
                formWindowClosing(evt);
            }
        });

        jLabelMessage.setText("Message");

        jTableVilles.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {

            }
        ));
        jScrollPane1.setViewportView(jTableVilles);

        jButtonTester.setText("Tester");
        jButtonTester.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonTesterActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 795, Short.MAX_VALUE)
                    .addComponent(jLabelMessage, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jButtonTester, javax.swing.GroupLayout.PREFERRED_SIZE, 149, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(0, 0, Short.MAX_VALUE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 128, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(42, 42, 42)
                .addComponent(jButtonTester)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 88, Short.MAX_VALUE)
                .addComponent(jLabelMessage)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing
//        try {
//            // TODO add your handling code here:
//            icn.close();
//        } catch (SQLException ex) {
//            Logger.getLogger(Table7JCombo.class.getName()).log(Level.SEVERE, null, ex);
//        }
    }//GEN-LAST:event_formWindowClosing

    private void jButtonTesterActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonTesterActionPerformed
        // TODO add your handling code here:
        for (int i = 0; i < jTableVilles.getRowCount(); i++) {
            System.out.println("valeur : " + jTableVilles.getValueAt(i, 2));
        }
    }//GEN-LAST:event_jButtonTesterActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(Table7JCombo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Table7JCombo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Table7JCombo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Table7JCombo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new Table7JCombo().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButtonTester;
    private javax.swing.JLabel jLabelMessage;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTableVilles;
    // End of variables declaration//GEN-END:variables
}
